//
//  CMPedometerHandle.swift
//  HSMainViewControllerHandler
//
//  Created by haisheng huang on 16/7/27.
//  Copyright © 2016年 haisheng huang. All rights reserved.
//

import Foundation
import CoreMotion



@available(iOS 8.0, *)
@objc open class CMPedometerHandle: NSObject {

    var pedometer: CMPedometer?
    
    override init() {
        self.pedometer = CMPedometer()
    }
    
    //计步是否有效
    class func isStepCountingAvailable() -> Bool {
        return CMPedometer.isStepCountingAvailable()
    }
    
    //距离估计是否有效
    class func isDistanceAvailable() -> Bool {
        return CMPedometer.isDistanceAvailable()
    }
    
    //楼层计算是否有效
    class func isFloorCountingAvailable() -> Bool {
        return CMPedometer.isFloorCountingAvailable()
    }
    
    //步速估计是否有效
    @available(iOS 9.0, *)
    class func isPaceAvailable() -> Bool {
        return CMPedometer.isPaceAvailable()
    }
    
    //节奏估计是否有效
    @available(iOS 9.0, *)
    class func isCadenceAvailable() -> Bool {
        return CMPedometer.isCadenceAvailable()
    }
    
    //开始计算一段时间内的计步情况
    func startPedometerUpdates(_ startDate: Date, handler: @escaping (CMPedometerData?, NSError?) -> Void) -> Void {
        
        self.pedometer?.startUpdates(from: startDate, withHandler: { (pedometerData, error) in
            handler(pedometerData, error as NSError?)
        })
    }
    
    //查询一段时间内的计步情况
    func queryPedometerData(_ startDate: Date, endDate: Date, handler: @escaping (CMPedometerData?, NSError?) -> Void) -> Void {
        
        self.pedometer?.queryPedometerData(from: startDate, to: endDate, withHandler: { (pedometerDate, error) in
            handler(pedometerDate, error as NSError?)
        })
    }
    
    //停止计步
    func stopPedometerUpdates() -> Void {
        if self.pedometer != nil {
            self.pedometer?.stopUpdates()
        }
    }
}
